<template>
  <div style="width: 95%;  margin: 0 auto; height: 100%; ">
    <!--    <div style="white-space: nowrap; height: 100%; display: flex; justify-content: flex-end; align-items: center;">-->
    <!--      <button class="btn bg-primary-heavy text-white"-->
    <!--              style="margin-right: 40px;"-->
    <!--              @click="update_agg_status">-->
    <!--        刷新-->
    <!--      </button>-->
    <!--    </div>-->
    <div class="container"
         style="white-space: nowrap; height: 100%; display: flex; justify-content: flex-start; align-items: center; margin-bottom: 10px;margin-top: 10px;padding: 0;">
      <h3 style="margin-right: 10px; line-height: 40px; margin-bottom: 0; margin-left: 5px;font-size: 20px; color: #000;font-weight: 600;">聚合服务器</h3>
      <!-- 设置与按钮相同的 line-height -->
      <button class="btn text-white"
              style="background-color: #ffffff; width: 30px; height: 30px; border: none; border-radius: 8px; display: flex; justify-content: center; align-items: center; padding: 0; margin: 0;"
              @click="update_agg_status">
        <i class="fas fa-sync" style="font-size: 16px; color: #aba8a8;"></i>
      </button>
    </div>
    <!--      <div class="card text-center p-3 m-2">-->
    <!--        <h3 class=" mb-3 mt-3">聚合服务器</h3>-->
    <!--      </div>-->

    <!-- 客户端模型状态 -->
    <div class="card text-center ms-2 me-4 mt-2 mb-2">
      <div class="card-body">
        <h5 class="">客户端模型接收情况</h5>
        <div class="table-responsive">
          <table class="table">
            <thead>
            <tr>
              <th scope="col">用户</th>
              <th v-for="(user, index) in Aggclients" :key="'user_' + index" scope="col" @click="showUserInfo(index)">
                {{ user.name }}
              </th>
            </tr>
            </thead>
            <tbody>
            <tr>
              <td>状态</td>
              <td class="text-white" v-for="(user, index) in Aggclients" :key="'user_status_' + index"
                  :class="{ 'bg-primary-heavy': user.status, 'bg-secondary-light': !user.status }"
                  @click="showUserInfo(index)"> {{ (user.status ? '已接收' : '未接收') }}
              </td>
            </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
    <!--           :class="{ 'bg-secondary': !state1||!state2, 'bg-primary': state1 && state2&& !button2State, 'bg-warning': state1 && state2&& button2State }"
    -->
    <!--服务端状态-->
    <div class="d-flex justify-content-center mt-2 mb-2">
      <div class="card mx-auto text-center ms-2 me-4 mt-2 mb-2"
           :class="{ 'bg-secondary': !state1||!Aggstates[0], 'bg-primary-heavy': state1 && Aggstates[0]&& !Aggstates[1], 'bg-warning': state1 && Aggstates[0] && Aggstates[1] }"
           style="width: 30%; aspect-ratio: 5/2;">
        <div class="card-body d-flex align-items-center justify-content-center" @click="showServerInfo">
          <h5 class="m-0 text-white">{{ serverstate }}</h5>
        </div>
      </div>
    </div>
    <!-- 按钮 -->
    <div style="white-space: nowrap; height: 200px;">
      <div class="card text-center">
        <div class="card-body">
          <div class="row mt-2 mb-2">
            <div class="col">
              <button class="btn bg-primary-heavy text-white btn-lg" @click="showInitConfirmation"
                      style="width: 100%; height: 100%" :disabled="buttons_status[0]">初始化
              </button>
            </div>

            <div class="col">
              <button class="btn bg-primary-heavy text-white btn-lg" @click="handleButtonClick(3)"
                      style="width: 100%; height: 100%" :disabled="buttons_status[1]">聚合模型
              </button>
            </div>
            <div class="col">
              <button class="btn bg-primary-heavy text-white btn-lg" @click="handleButtonClick(4)"
                      style="width: 100%; height: 100%" :disabled="buttons_status[2]">分发模型
              </button>
            </div>
            <div class="col">
              <button class="btn btn-lg" disabled
                      :class="{ 'btn-warning': Aggstates[1], 'bg-primary-heavy text-white': !Aggstates[1] }"
                      style="width: 100%; height: 100%">
                {{ button2Text }}
              </button>
            </div>
            <div class="col">
              <button class="btn btn-warning btn-lg" @click="handleButtonClick(5)" style="width: 100%; height: 100%">
                设置服务器恶意
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <!-- 模态窗口 (动效窗口) -->
  <div v-if="isModalVisible" class="modal-overlay">
    <div class="modal-content">
      <div class="spinner"></div>
      <h5 class="text-center  mt-3">处理中，请稍候...</h5>
    </div>
  </div>
  <!-- 初始化弹窗 -->
  <div v-if="isInitConfirmationVisible" class="modal">
    <div class="modal-content">
      <h4>初始化</h4>
      <p>您确定要执行初始化操作吗？</p>
      <button class="btn bg-primary-heavy  text-white" @click="handleButtonClick(1)">确认</button>
      <button class="btn btn-secondary" @click="cancelInit">取消</button>
    </div>
  </div>
  <CustomAlert ref="customAlert" />
</template>

<script setup>
import {ref, computed, onMounted, onUnmounted} from 'vue';
import axios from "axios";
// import { io } from 'socket.io-client';
import {useStore} from "vuex";

// import Swal from 'sweetalert2';
import CustomAlert from './CustomAlert.vue';

const customAlert=ref(null);
// function customAlert(message) {
//   return Swal.fire({
//     text: message,
//     showConfirmButton: false,
//     showCancelButton: true,
//     cancelButtonText: '确认',
//     cancelButtonColor: '#253cc2'
//   });
// }

// 使用 async/await 来模拟阻塞
// async function showAlert(message) {
//   await customAlert(message);
//   console.log(message);
// }
// const showAlert = (text) => {
//   Swal.fire({
//     text: text,
//     // icon: 'info',
//     focusCancel:true,
//     showConfirmButton: false,
//     showCancelButton: true,
//     cancelButtonText: '确认',
//     cancelButtonColor: '#253cc2'
//   }).then((result) => {
//   if (!result.isConfirmed) {
//     // 用户点击了确认按钮
//     console.log(text)
//     // 在这里执行你希望在点击确认按钮后进行的操作
//   }
// })
//
// };

// 所有user状态为true时，state1为true
const state1 = computed(() => Aggclients.value.every(user => user.status === true));
// const state1 = ref(true);
// const state2 = ref(false);
// const state3 = ref(false);
// const button2State = ref(false); // 初始状态为 true
const button2Text = ref('服务器诚实'); // 初始文本为 '状态2'


const initialStates = [false, false, 'server information']
const initialClients = [
  {name: 'user1', client_id: '1', status: false, info: 'User 1 information'},
  {name: 'user2', client_id: '1', status: false, info: 'User 2 information'},
  {name: 'user3', client_id: '1', status: false, info: 'User 1 information'},
  {name: 'user4', client_id: '1', status: false, info: 'User 2 information'},
  {name: 'user5', client_id: '1', status: false, info: 'User 1 information'},
]
const Aggclients = ref([]);
const Aggstates = ref([]);
const buttons_status = ref([false, true, true])

// 从本地存储中获取用户设置
const loadAggclientsFromSessionStorage = (option) => {
  if (option === 1) {
    const storedAggClients = JSON.parse(sessionStorage.getItem('Aggclients'));
    if (storedAggClients) {
      Aggclients.value = storedAggClients;
    } else {
      Aggclients.value = [...initialClients];
    }
  }
  if (option === 2) {
    const storedAggstates = JSON.parse(sessionStorage.getItem('Aggstates'));
    console.log("storedAggstates:", storedAggstates)
    if (storedAggstates) {
      Aggstates.value = storedAggstates;
    } else {
      Aggstates.value = [...initialStates];
    }
  }
};

// 将用户设置保存到本地存储
const saveAggclientsToSessionStorage = (option) => {
  if (option === 1) {
    sessionStorage.setItem('Aggclients', JSON.stringify(Aggclients.value));
  }
  if (option === 2) {
    sessionStorage.setItem('Aggstates', JSON.stringify(Aggstates.value));
  }
};

// 向后端获取前端状态
const update_agg_status = async () => {
  loadAggclientsFromSessionStorage(1);
  loadAggclientsFromSessionStorage(2);
  try {
    // 发送 Localuser 数据给后端
    const response = await apiAgg.get('/agg_status');
    if (response.status === 200) {
      console.log(response.data)
      const clients = response.data.clients;
      const states = response.data.states;
      console.log("返回的客户端数据:", response.data);
      // 动态生成客户端信息
      Aggclients.value = clients.map(client => ({
        // name: `user${client['id'] }`, // 使用序号生成名称
        name: client['name'],
        client_id: client['client_id'],
        status: client['status'], // 初始状态
        userid: client['userid'],
        // username:client['username'],
        info: `User ${client['name']} information` // 默认信息

      }));
      Aggstates.value = [...states]
      // Aggstates.value = states.map((state) => ({
      //   // name: `user${client['id']}`,
      //   name:state['username'],
      //   client_id: state[0],
      //   status: state[1],
      //   userid: state[2],
      //   // username : client['username']
      // }));
      // 设置按钮状态
      set_buttons(response.data.step_status);
      saveAggclientsToSessionStorage(1);
      saveAggclientsToSessionStorage(2);
    }
  } catch (error) {
    console.error('更新用户信息失败:', error);
  }
};

// 按钮状态赋值
const set_buttons = async (step_status) => {
  if (step_status === "step_none") {
    buttons_status.value = [false, true, true];
  } else if (step_status === "step_init_done") {
    buttons_status.value = [true, false, true];
  } else if (step_status === "step_agg_done") {
    buttons_status.value = [true, true, false];
  } else if (step_status === "step_post_done") {
    buttons_status.value = [true, false, true];
  }
  console.log("buttons_status:", buttons_status.value)
};
// 页面锁定
// const isLocked = ref(false); // 控制锁定状态

const store = useStore();
const hideSidebar = () => store.commit('hideSidebar');
const showSidebar = () => store.commit('showSidebar');
// 组件挂载时加载用户设置
onMounted(() => {
  hideSidebar();
  loadAggclientsFromSessionStorage(1);
  loadAggclientsFromSessionStorage(2);
  update_agg_status();
  button2Text.value = Aggstates.value[1] ? '服务器恶意' : '服务器诚实';
  console.log("Aggstates", Aggstates.value);

  // connectWebSocket();
});

// 组件卸载时保存用户设置到本地存储
onUnmounted(() => {
  showSidebar();
  saveAggclientsToSessionStorage(1);
  saveAggclientsToSessionStorage(2);
  // if (socket) {
  //   socket.disconnect();
  // }
});

//设置axios
const apiBaseUrl = window.webConfig && window.webConfig.ServerAggBaseUrl;
const apiAgg = axios.create({
  baseURL: apiBaseUrl,
  headers: {
    'Content-Type': 'application/json'
  }
});
// WebSocket setup
// let socket;
// const connectWebSocket = () => {
//   socket = io(apiBaseUrl); // 请确保这个 URL 与后端 WebSocket 服务器一致
//
//   socket.on('connect', () => {
//     console.log('WebSocket connected');
//   });
//
//   socket.on('update_client',(data) => {
//   let { client_id, status, info } = data;
//   const client = Aggclients.value.find(client => client.client_id === client_id);
//   if (client) {
//     client.status = status;
//     client.info = info;
//     saveAggclientsToSessionStorage(1); // 保存更新后的数据到本地存储
//   }
//   });
//
//   socket.on('disconnect', () => {
//     console.log('WebSocket disconnected, reconnecting...');
//     setTimeout(connectWebSocket, 1000);
//   });
// };

const showUserInfo = (index) => {
  const user = Aggclients.value[index];
  // showAlert(user.name + " client_id:" + user.client_id + " userid:" + user.userid + " information: " + user.info);// 在真实应用中，你可以使用自定义的弹窗组件来展示用户信息
  customAlert.value.open(user.name + " client_id:" + user.client_id + " userid:" + user.userid + " information: " + user.info);
  console.log(`Clicked on column ${index}`);
};

const showServerInfo = () => {
  // showAlert("Server information: " + Aggstates.value[2]);// 在真实应用中，你可以使用自定义的弹窗组件来展示用户信息
  customAlert.value.open("Server information: " + Aggstates.value[2]);
  console.log(`Clicked on Server`);
}

const serverstate = computed(() => {
  if (!state1.value) {
    return '未聚合';
  } else {
    if (!Aggstates.value[0]) {
      return '未聚合'; // 如果 state1 为 false，标题的类名为 m-0 text-white
    } else {
      if (!Aggstates.value[1]) {
        return '服务器诚实'; // 如果 state1 为 false，标题的类名为 m-0 text-white
      } else {
        return '服务器恶意';
      }
    }
  }
});

//用于初始化
const isInitConfirmationVisible = ref(false);
const showInitConfirmation = () => {
  isInitConfirmationVisible.value = true;
};
const cancelInit = () => {
  isInitConfirmationVisible.value = false;
};
const isModalVisible = ref(false);  // 控制模态窗口显示状态
const isButtonClicked = ref(false);
const handleButtonClick = async (buttonNumber) => {
  try {
    isInitConfirmationVisible.value = false;
    // 检查按钮是否已经被点击，如果是，则直接返回
    if (isButtonClicked.value) {
      await customAlert.value.open('正在等待上一次请求的响应，请稍后...');
      // showAlert('正在等待上一次请求的响应，请稍后...');
      console.log('按钮已经被点击，正在等待上一次请求的响应...');
      return;
    }
    // 按钮被点击，设置状态为 true
    isButtonClicked.value = true;
    isModalVisible.value = true;
    let response;

    switch (buttonNumber) {
      case 1:
        // showAlert("聚合服务器开始初始化...")
        // showAlert("聚合服务器开始初始化...")
        await customAlert.value.open("聚合服务器开始初始化...");
        Aggstates.value = [...initialStates];
        button2Text.value = Aggstates.value[1] ? '服务器恶意' : '服务器诚实';
        // 查看追踪服务器是否已经初始化
        try {
          const response = await apiAgg.get('/agg_status');
          if (response.status === 200) {
            console.log(response.data)
            const trace_state = response.data.trace_step_status;
            console.log("trace_step_status:", response.data);
            if (trace_state === "step_none") {
              // showAlert("追踪服务器尚未完成初始化，请稍后重试");
              await customAlert.value.open("追踪服务器尚未完成初始化，请稍后重试");
            } else {
              const response1 = await apiAgg.post(`/init`);
              if (response1.status === 200) {
                const clients = response1.data.clients_simpledata;
                console.log("返回的客户端数据:", response1.data);
                // 动态生成客户端信息
                Aggclients.value = clients.map(client => ({
                  // name: `user${client['id'] }`, // 使用序号生成名称
                  name: client['username'],
                  client_id: client['client_id'],
                  status: false, // 初始状态
                  userid: client['userid'],
                  // username:client['username'],
                  info: `User ${client['id']} information` // 默认信息

                }));
                console.log("更新后的 Aggclients:", Aggclients.value);
                console.log("更新后的 Aggstates:", Aggstates.value);
                update_agg_status();
                // 保存更新后的数据到本地存储
                saveAggclientsToSessionStorage(1);
                saveAggclientsToSessionStorage(2);
                // showAlert("聚合服务器初始化完成")
                await customAlert.value.open("聚合服务器初始化完成");
              }
              console.log('按钮1的响应:', response1.data);
            }

          }
        } catch (error) {
          console.error('更新用户信息失败:', error);
        }


        break;
      case 3:
        // 发送请求
        // response = await axios.post(`${process.env.VUE_APP_BACKEND_API}/AggServer`,{task:"aggregate",server_state : Aggstates.value[1] });

        response = await apiAgg.get('/agg_status');
        if (response.status === 200) {
          console.log(response.data)
          const trace_state = response.data.trace_step_status;
          console.log("trace_step_status:", response.data);
          if (trace_state === "step_none") {
            // showAlert("全局状态已重置，请重新初始化");
            await customAlert.value.open("全局状态已重置，请重新初始化");
            response = await apiAgg.get('/agg_status');
            if (response.status === 200) {
              console.log(response.data)
              const clients = response.data.clients;
              const states = response.data.states;
              console.log("返回的客户端数据:", response.data);
              // 动态生成客户端信息
              Aggclients.value = clients.map(client => ({
                // name: `user${client['id'] }`, // 使用序号生成名称
                name: client['name'],
                client_id: client['client_id'],
                status: client['status'], // 初始状态
                userid: client['userid'],
                // username:client['username'],
                info: `User ${client['name']} information` // 默认信息

              }));
              Aggstates.value = [...states]
              // 设置按钮状态
              set_buttons(response.data.step_status);
              saveAggclientsToSessionStorage(1);
              saveAggclientsToSessionStorage(2);
            }
          } else {
            if (state1.value) {
              // showAlert("开始聚合本地模型")
              await customAlert.value.open("开始聚合本地模型");
              response = await apiAgg.post(`/aggregate`, {server_state: Aggstates.value[1]});
              console.log(response.data);
              if (response.status === 200) {
                Aggstates.value[0] = true
                saveAggclientsToSessionStorage(2);
                if (response.data.verify_aggregation === 0) {
                  await customAlert.value.open("服务器聚合验证未通过，请重新开始训练");
                  // showAlert("服务器聚合验证未通过，请重新开始训练")
                  Aggstates.value[0] = false
                } else {
                  Aggstates.value[2] = response.data.aggregation_model || Aggstates.value[2];
                  // 将初始数据保存到本地存储
                  saveAggclientsToSessionStorage(2);
                  await customAlert.value.open("模型聚合完成");
                  // showAlert("模型聚合完成");
                  console.log('按钮3的响应:', response.data);
                  update_agg_status();
                }
              }
            } else {
              await customAlert.value.open("客户端模型未上传完成，请稍后重试");
              // showAlert("客户端模型未上传完成，请稍后重试")
            }
          }
        }

        break;
      case 4:

        response = await apiAgg.get('/agg_status');
        if (response.status === 200) {
          console.log(response.data)
          const trace_state = response.data.trace_step_status;
          console.log("trace_step_status:", response.data);
          if (trace_state === "step_none") {
            await customAlert.value.open("全局状态已重置，请重新初始化");
            // showAlert("全局状态已重置，请重新初始化");
            response = await apiAgg.get('/agg_status');
            if (response.status === 200) {
              console.log(response.data)
              const clients = response.data.clients;
              const states = response.data.states;
              console.log("返回的客户端数据:", response.data);
              // 动态生成客户端信息
              Aggclients.value = clients.map(client => ({
                // name: `user${client['id'] }`, // 使用序号生成名称
                name: client['name'],
                client_id: client['client_id'],
                status: client['status'], // 初始状态
                userid: client['userid'],
                // username:client['username'],
                info: `User ${client['name']} information` // 默认信息

              }));
              Aggstates.value = [...states]
              // 设置按钮状态
              set_buttons(response.data.step_status);
              saveAggclientsToSessionStorage(1);
              saveAggclientsToSessionStorage(2);
            }
          } else {
            if (Aggstates.value[0]) {
              // 发送请求
              // showAlert("分发聚合结果")
              await customAlert.value.open("分发聚合结果");
              response = await apiAgg.post(`/post_agg_result`);

              if (response.status === 200) {
                // showAlert("分发完成")
                await customAlert.value.open("分发完成");
                Aggclients.value.forEach(client => {
                  client.status = false;
                });
                Aggstates.value = [...initialStates]
                button2Text.value = Aggstates.value[1] ? '服务器恶意' : '服务器诚实';
              }
              console.log('按钮3的响应:', response.data);
            } else {
              // showAlert("尚未执行聚合操作，请稍后重试")
              await customAlert.value.open("尚未执行聚合操作，请稍后重试");
            }
          }
        }
        update_agg_status();
        break;
      case 5:
        Aggstates.value[1] = !Aggstates.value[1]
        button2Text.value = Aggstates.value[1] ? '服务器恶意' : '服务器诚实';
        saveAggclientsToSessionStorage(2);
        loadAggclientsFromSessionStorage(2);
        break;
      default:
        console.error('未知的按钮编号:', buttonNumber);
        break;
    }
  } catch (error) {
    console.error('请求失败:', error);
  } finally {
    isButtonClicked.value = false;
    isModalVisible.value = false;  // 请求完成后关闭模态窗口
  }
};
</script>


<style scoped nonce="randomNonceValue">
table {
  width: 100%;
  margin-bottom: 1rem;
  color: #212529;
  border-collapse: separate;
  border-spacing: 1px 2px;
}

.bg-primary-light {
  background-color: #5e72e4 !important; /* 淡蓝色 */
}

.bg-secondary-light {
  background-color: #aba8a8 !important; /* 淡灰色 */
}

.btn-secondary.disabled {
  pointer-events: none;
  opacity: 1;
}

.disabled1 {
  pointer-events: none;
  opacity: 1;
}

.bg-primary-heavy {
  background-color: #152ca8 !important; /* 淡蓝色 */
}

.bg-danger-light {
  background-color: #a12004 !important; /* 淡灰色 */
}

.btn-secondary.disabled {
  pointer-events: none;
  opacity: 1;
}

.disabled1 {
  pointer-events: none;
  opacity: 1;
}

/*窗口动效*/
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  width: 30%; /* 宽度 */
  aspect-ratio: 16/6;
  background-color: #c9dafc;
  padding: 20px;
  border-radius: 8px;
  text-align: center;
}

.spinner {
  border: 4px solid rgba(255, 255, 255, 0.2);
  border-left-color: #152ca8;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/*初始化弹窗*/
.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-content {
  background: white;
  padding: 20px;
  border-radius: 5px;
  text-align: center;
}
.col {
  margin: 10px 0;
}
</style>